<template>
  <view class="addressBook">
    <pit-header title="通讯录" :showBack="false"></pit-header>
    <pit-search></pit-search>
    <view class="addr-select">
      <view class="addr-select-text" :style="{ color: (breadcrumbList.length === 0 ) ? '#409eff' : 'gray'  }"
        @click="goToInitial">请选择
      </view>
      <scroll-view class="addr-select-scroll" scroll-x :show-scrollbar="false" v-if="breadcrumbList.length">
        <text v-for="(item, index) in breadcrumbList" :key="index" class="addr-select-item" @click="goBack(index)"
          :style="{ color: index === activeLevel ? '#409eff' : 'gray' }">
          {{ item }}
          <text v-if="index !== breadcrumbList.length - 1" class="addr-select-item-icon"> &gt; </text>
        </text>
      </scroll-view>
    </view>
    <view class="addr-list">
      <template v-if="isSearching ? filteredData.length : currentData.length">
        <block v-for="(item, index) in (isSearching ? filteredData : currentData)" :key="index">
          <view v-if="item.type === 'folder'" class="addr-list-file" @click="enterFolder(item)">
            <img src="/static/addressBook/file.png" alt="file" mode="aspectFill" style="width: 37px;" />
            <text class="addr-list-file-name">{{ item.fullName}}</text>
            <img src="/static/addressBook/arrow_up.png" alt="next" mode="aspectFill" style="width: 20px;" />
          </view>
          <view v-else-if="item.type === 'user'" class="addr-list-person" @click="goToProfile(item)">
            <img src="/static/addressBook/personnel.png" alt="person" mode="aspectfile" style="width: 40px;" />
            <text class="addr-list-person-name">{{ item.fullName}}</text>
          </view>
        </block>
      </template>
      <view v-else class="addr-list-empty">暂无数据</view>
    </view>
  </view>
</template>

<script>
  import {
    apiAppMailListGetProjectUser
  } from '@/api/app/mailList'
  export default {
    data() {
      return {
        sourceData: [],
        breadcrumbList: [],
        currentData: [],
        searchKey: '',
        filteredData: [],
        activeLevel: 0,
      };
    },
    onLoad() {
      this.init();
    },
    computed: {
      isSearching() {
        return this.searchKey.trim() !== '';
      }
    },
    methods: {
      init() {
        apiAppMailListGetProjectUser({
          projectId: uni.getStorageSync("projectId")
        }).then(res => {
          if (res.code === '00000') {
            const folderTypes = ['DW', 'company', 'organization', 'bid'];
            const formatData = (data) => {
              return data.map(item => {
                const hasChildren = item.children && item.children.length > 0;
                const isFolderType = folderTypes.includes(item.type);
                const formatted = {
                  ...item,
                  type: isFolderType ? 'folder' : 'user',
                  isEmptyFolder: isFolderType && !hasChildren,
                  children: item.children ? formatData(item.children) : []
                };
                return formatted;
              });
            };
            this.sourceData = formatData(res.data);
            this.currentData = this.sourceData || [];
            this.breadcrumbList = [];
          } else {
            uni.showToast({
              title: '通讯录调取失败',
              icon: 'none'
            })
          }
        });
      },
      enterFolder(item) {
        if (item.isEmptyFolder) {
          uni.showToast({
            title: "暂无联系人",
            icon: "none"
          });
          return
        }
        this.breadcrumbList.push(item.fullName);
        this.currentData = item.children || [];
        this.searchKey = '';
        this.filteredData = [];
        this.activeLevel = this.breadcrumbList.length - 1;
      },
      goBack(level) {
        if (level < 0 || level >= this.breadcrumbList.length) return;

        this.breadcrumbList = this.breadcrumbList.slice(0, level + 1);
        this.activeLevel = level;
        let targetData = this.sourceData;
        for (let i = 0; i < this.breadcrumbList.length; i++) {
          const currentName = this.breadcrumbList[i];
          const foundItem = targetData.find(item => item.fullName === currentName);
          targetData = foundItem ? foundItem.children || [] : [];
        }
        this.currentData = targetData;
        this.searchKey = '';
        this.filteredData = [];
      },
      goToProfile(person) {
        uni.setStorageSync('currentPerson', person);
        uni.navigateTo({
          url: '/pages/other/addressBookpages/personalIform/personalInform',
        });
      },
      goToInitial() {
        this.breadcrumbList = [];
        this.currentData = this.sourceData || [];
        this.searchKey = '';
        this.filteredData = [];
        this.activeLevel = 0;
      },
    }
  }
</script>

<style lang="scss" scoped>
  .addressBook {
    display: flex;
    flex-direction: column;
    width: 100%;
    min-height: 100vh;
    background: rgb(246, 246, 246);

    .separator {
      color: #999;
      margin: 0 5px;
    }

    .addr-select {
      padding: 10px;
      background-color: #f8f9fb;
      height: 25px;
      display: flex;
      align-items: center;

      .addr-select-text {
        width: 60px;
        font-size: 15px;
        flex-shrink: 0;
      }

      .addr-select-scroll {
        width: 100%;
        white-space: nowrap;
        overflow: hidden;

        ::-webkit-scrollbar {
          display: none;
        }

        .addr-select-item {
          font-size: 15px;
          cursor: pointer;
        }

        .addr-select-item-icon {
          color: #999;
          margin: 0 5px;
        }
      }
    }

    .addr-list {
      flex: 1;
      overflow-y: auto;
      background-color: white;
      max-height: calc(100vh - 230px);

      .addr-list-file,
      .addr-list-person {
        display: flex;
        align-items: center;
        padding: 10px;
        border-bottom: 2px solid #f2f2f2;
      }

      .addr-list-file-name,
      .addr-list-person-name {
        flex: 1;
        margin-left: 12px;
        font-size: 15px;
        font-weight: 400;
        color: black;
      }

      .addr-list-file-name.active {
        color: gray;
      }

      .addr-list-empty {
        text-align: center;
        color: #999;
        padding: 30px 0;
        font-size: 14px;
      }
    }
  }
</style>
